package cn.edu.hunau.service;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class SensorDataSenderService {

    @Autowired
    private MessageChannel mqttOutputChannel;

    private final Random random = new Random();


    @Scheduled(fixedRate = 5000)
    public void sendJSONSensorData() throws Exception {
       Map<String,Object> datas= generateSimulatedData();

        ObjectMapper mapper = new ObjectMapper();
       String json = mapper.writeValueAsString(datas);
        System.out.println(json);
        mqttOutputChannel.send(new GenericMessage<>(json));
    }

    public   Map<String, Object> generateSimulatedData() {
        Map<String, Object> data = new HashMap<>();
        data.put("device_id", "agri_sensor_01");

        // 生成时间戳
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String timestamp = dateFormat.format(new Date());
        data.put("timestamp", timestamp);

        // 模拟温度，范围 15 到 35 摄氏度
        double temperatureData = 15 + random.nextDouble() * 20;
        // 模拟湿度，范围 30% 到 80%
        double humidityData = 30 + random.nextDouble() * 50;
        // 模拟二氧化碳浓度，范围 300 到 1000 ppm
        double co2ConcentrationData = 300 + random.nextDouble() * 700;
        // 模拟土壤湿度，范围 20% 到 70%
        double soilMoistureData = 20 + random.nextDouble() * 50;

        // 温度数据
        Map<String, Object> temperature = generateSensorData(decimal(temperatureData,2), 20.0, 35.0);
        data.put("temperature", temperature);

        // 湿度数据
        Map<String, Object> humidity = generateSensorData(decimal(humidityData,2), 60.0, 85.0);
        data.put("humidity", humidity);

        // 土壤湿度数据
        Map<String, Object> soilMoisture = generateSensorData(decimal(soilMoistureData,2),65.0, 85.0);
        data.put("soil_moisture", soilMoisture);

        // 二氧化碳浓度数据
        Map<String, Object> co2Concentration = generateSensorData(decimal(co2ConcentrationData,2), 350.0, 550.0);
        data.put("co2_concentration", co2Concentration);

        return data;
    }

    private   Map<String, Object> generateSensorData(double value, double lowThreshold, double highThreshold) {
        Map<String, Object> sensorData = new HashMap<>();
        sensorData.put("value", value);

        Map<String, Double> threshold = new HashMap<>();
        threshold.put("low", lowThreshold);
        threshold.put("high", highThreshold);
        sensorData.put("threshold", threshold);

        boolean isOutOfRange = value < lowThreshold || value > highThreshold;
        sensorData.put("is_out_of_range", isOutOfRange);




        return sensorData;
    }



    public void sendMultipleSensorData() {
        // 模拟温度，范围 15 到 35 摄氏度
        double temperature = 15 + random.nextDouble() * 20;
        // 模拟湿度，范围 30% 到 80%
        double humidity = 30 + random.nextDouble() * 50;
        // 模拟二氧化碳浓度，范围 300 到 1000 ppm
        double co2Concentration = 300 + random.nextDouble() * 700;
        // 模拟害虫数量，范围 0 到 200
        int pestCount = random.nextInt(200);
        // 模拟光照强度，范围 1000 到 10000 lux
        double lightIntensity = 1000 + random.nextDouble() * 9000;
        // 模拟土壤湿度，范围 20% 到 70%
        double soilMoisture = 20 + random.nextDouble() * 50;
        // 模拟土壤酸碱度，范围 5.5 到 7.5
        double soilPH = 5.5 + random.nextDouble() * 2;

        String temperatureAlert = "";
        String humidityAlert = "";
        String co2Alert = "";
        String pestAlert = "";
        String lightAlert = "";
        String soilMoistureAlert = "";
        String soilPHAlert = "";

        // 温度预警判断
        if (temperature < 18) {
            temperatureAlert = "温度过低";
        } else if (temperature > 32) {
            temperatureAlert = "温度过高";
        }

        // 湿度预警判断
        if (humidity < 35) {
            humidityAlert = "湿度过低";
        } else if (humidity > 75) {
            humidityAlert = "湿度过高";
        }

        // 二氧化碳浓度预警判断
        if (co2Concentration < 400) {
            co2Alert = "二氧化碳浓度过低";
        } else if (co2Concentration > 800) {
            co2Alert = "二氧化碳浓度过高";
        }

        // 害虫数量预警判断
        if (pestCount > 100) {
            pestAlert = "害虫数量过多";
        }

        // 光照强度预警判断
        if (lightIntensity < 2000) {
            lightAlert = "光照强度过低";
        } else if (lightIntensity > 8000) {
            lightAlert = "光照强度过高";
        }

        // 土壤湿度预警判断
        if (soilMoisture < 25) {
            soilMoistureAlert = "土壤湿度过低";
        } else if (soilMoisture > 65) {
            soilMoistureAlert = "土壤湿度过高";
        }

        // 土壤酸碱度预警判断
        if (soilPH < 6) {
            soilPHAlert = "土壤过酸";
        } else if (soilPH > 7) {
            soilPHAlert = "土壤过碱";
        }

        String sensorData = String.format("{\"temperature\": %.2f, \"humidity\": %.2f, \"co2Concentration\": %.2f, \"pestCount\": %d, \"lightIntensity\": %.2f, \"soilMoisture\": %.2f, \"soilPH\": %.2f, " +
                        "\"temperatureAlert\": \"%s\", \"humidityAlert\": \"%s\", \"co2Alert\": \"%s\", \"pestAlert\": \"%s\", \"lightAlert\": \"%s\", \"soilMoistureAlert\": \"%s\", \"soilPHAlert\": \"%s\"}",
                temperature, humidity, co2Concentration, pestCount, lightIntensity, soilMoisture, soilPH,
                temperatureAlert, humidityAlert, co2Alert, pestAlert, lightAlert, soilMoistureAlert, soilPHAlert);
          mqttOutputChannel.send(new GenericMessage<>(sensorData));
         System.out.println("Sent sensor data: " + sensorData);
    }


  //  @Scheduled(fixedRate = 10000) // 每 10 秒执行一次
    public void sendSensorData() {
        double temperature = 20 + random.nextDouble() * 10; // 模拟温度 20 - 30 度
        double humidity = 40 + random.nextDouble() * 20; // 模拟湿度 40 - 60 %

        String sensorData = "{\"temperature\": " + decimal(temperature,2) + ", \"humidity\": " + decimal(humidity,2) + "}";
        mqttOutputChannel.send(new GenericMessage<>(sensorData));
        System.out.println("Sent sensor data: " + sensorData);
    }


    private double decimal(double value,int decimal){
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(decimal, RoundingMode.HALF_UP); // 四舍五入
         return bd.doubleValue();

    }
}